<script setup lang='ts'>
import type { OptionsType } from 'plus-pro-components'

import { useEditEnterprise, useGetAllSupplierTree, useGetEnterpriseInfo, useGetEnterpriseType, useGetServiceCategory } from '@fl/api/man-api'
import { downTpl } from '@fl/api/man-api/jc-authentication'
import { SearchForm } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

import { useRule } from './use-rule'

const instance = getCurrentInstance()
const { rules } = useRule(instance)
const formRef = ref()
const { createMessage } = useMessage()
const props = { multiple: true }
const { query } = useRoute()
const { go } = useRouter()

const fileType = '.rar,.zip,.doc,.docx,.pdf,.jpg,.jpeg,.png,.xlsx'

const state = ref<any>({
    accountName: '',
    accountNumber: '',
    attachmentsAuthorizationLetterList: [],
    bankName: '',
    businessLicenseAttachmentsList: [],
    businessPeriod: '',
    cat: [],
    contactCardNo: '',
    contactMobile: '',
    contactName: '',
    enterpriseName: '',
    enterpriseSecondType: '',
    establishmenDate: '',
    legalCard: '',
    legalMobile: '',
    legalRepresentative: '',
    logo: '',
    projectPerformanceList: [],
    qualificationDocumentList: [],
    registeredAddress: '',
    registeredCapital: '',
    supplyCat: '',
    unifiedSocialCreditCode: '',
})

const key = ref(1)
const id = ref(query?.id as string)
const { data: enterpriseInfo, isLoading: isEnterpriseInfo } = useGetEnterpriseInfo(id)
const { data: serviceCategoryOptions, isLoading: isServiceCategoryLoading } = useGetServiceCategory()
const { data: supplierTree } = useGetAllSupplierTree()

const type = computed(() => Number(state.value.enterpriseType) + 1)

const { data: enterpriseTypeList } = useGetEnterpriseType(type)
const { isPending, mutate } = useEditEnterprise()
const isLoading = computed(() => isEnterpriseInfo.value || isServiceCategoryLoading.value || isPending.value)

const disabled = computed(() => false)
const changeBusinessLicenseAttachmentsList = ref(false)
const changeAttachmentsAuthorizationLetterList = ref(false)

const finalGroup: any = computed(() => {
    return [
        {
            columns: [
                {
                    fieldProps: {
                        disabled: true,
                    },
                    label: '统一社会信用代码',
                    prop: 'unifiedSocialCreditCode',
                    valueType: 'input',
                },
                {

                    fieldProps: {
                        disabled,
                    },
                    label: '公司名称',
                    prop: 'enterpriseName',
                    valueType: 'input',
                },
                {

                    fieldProps: {
                        disabled,
                    },
                    label: '法定代表人',
                    prop: 'legalRepresentative',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                        type: 'datetime',
                        valueFormat: 'YYYY-MM-DD HH:mm:ss',
                    },
                    label: '成立日期',
                    prop: 'establishmenDate',
                    valueType: 'date-picker',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '营业期限',
                    prop: 'businessPeriod',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '注册资本',
                    prop: 'registeredCapital',
                    valueType: 'input',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '企业LOGO',
                    prop: 'logo',

                },
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: {
                        disabled,
                    },
                    label: '注册地址',
                    prop: 'registeredAddress',
                    valueType: 'input',
                },

            ],
            title: '工商信息(数据来源于企查查)',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    fieldProps: { disabled, props },
                    label: '服务类别',
                    options: serviceCategoryOptions as OptionsType,
                    prop: 'cat',
                    valueType: 'cascader',
                },

            ],
            hideInGroup: computed(() => query?.source !== 'manufacturer'),
            title: '产品服务',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '姓名',
                    prop: 'legalRepresentative',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '电话',
                    prop: 'legalMobile',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '身份证号码',
                    prop: 'legalCard',
                    valueType: 'input',
                },
            ],
            title: '法人信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '姓名',
                    prop: 'contactName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '电话',
                    prop: 'contactMobile',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '身份证号码',
                    prop: 'contactCardNo',
                    valueType: 'input',
                },
            ],
            title: '联系人信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '开户名',
                    prop: 'accountName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '开户行',
                    prop: 'bankName',
                    valueType: 'input',
                },
                {
                    fieldProps: {
                        disabled,
                    },
                    label: '银行账号',
                    prop: 'accountNumber',
                    valueType: 'input',
                },
            ],
            title: '账户信息',
        },
        {
            columns: [
                {
                    fieldProps: {
                        disabled,
                    },
                    label: computed(() => {
                        return Number(state.value.enterpriseType) === 0 ? `采购商类型` : `供应商类型`
                    }),
                    options: computed(() => {
                        return enterpriseTypeList.value || []
                    }),
                    prop: 'enterpriseSecondType',
                    valueType: 'select',
                    width: 120,
                },
                {

                    fieldProps: {
                        disabled,
                        props: {
                            multiple: true,

                        },
                        showAllLevels: false,
                    },
                    hideInForm: computed(() => !(Number(state.value.enterpriseType) === 1)),
                    label: '供应商类别',
                    options: computed(() => {
                        return supplierTree.value || []
                    }),
                    prop: 'supplyCat',
                    valueType: 'cascader',
                    width: 120,
                },

            ],
            title: '机构类型',
        },
        {
            columns: [
                {
                    colProps: {
                        span: 24,
                    },
                    label: '营业执照附件',
                    prop: 'businessLicenseAttachmentsList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '授权函',
                    prop: 'attachmentsAuthorizationLetterList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '资质文件',
                    prop: 'qualificationDocumentList',
                },
                {
                    colProps: {
                        span: 24,
                    },
                    label: '项目业绩',
                    prop: 'projectPerformanceList',
                },
            ],
            title: '附件信息(仅修改企业信息上传)',
        },
    ]
})

watchEffect(() => {
    if (enterpriseInfo.value) {
        const businessLicenseAttachmentsList = enterpriseInfo.value.jcEnterpriseInfoPart.businessLicenseAttachmentsList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const attachmentsAuthorizationLetterList = enterpriseInfo.value.jcEnterpriseInfoPart.attachmentsAuthorizationLetterList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const qualificationDocumentList = enterpriseInfo.value.jcEnterpriseInfoPart.qualificationDocumentList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        const projectPerformanceList = enterpriseInfo.value.jcEnterpriseInfoPart.projectPerformanceList?.map((v: any) => {
            return { name: v.fileName || v.name, url: v.fileUrl || v.url }
        }) || []
        state.value = {
            ...enterpriseInfo.value.jcEnterpriseInfoPart,
            attachmentsAuthorizationLetterList,
            businessLicenseAttachmentsList,
            cat: enterpriseInfo.value.jcEnterpriseInfoPart?.cat && JSON.parse(enterpriseInfo.value.jcEnterpriseInfoPart?.cat),
            enterpriseSecondType: `${enterpriseInfo.value.jcEnterpriseInfoPart?.enterpriseSecondType}`,
            logo: enterpriseInfo.value.jcEnterpriseInfoPart?.logo || '',
            projectPerformanceList,
            qualificationDocumentList,
            supplyCat: enterpriseInfo.value.jcEnterpriseInfoPart?.supplyCat ? JSON.parse(enterpriseInfo.value.jcEnterpriseInfoPart?.supplyCat) : [],
        }

        key.value++
    }
})

async function sumbit() {
    const isVal = await formRef.value.formInstance.handleSubmit()
    if (!isVal) {
        return
    }
    const target = cloneDeep(state.value)

    if ((target.enterpriseName !== enterpriseInfo.value.jcEnterpriseInfoPart.enterpriseName
        || target.legalRepresentative !== enterpriseInfo.value.jcEnterpriseInfoPart.legalRepresentative
        || target.registeredAddress !== enterpriseInfo.value.jcEnterpriseInfoPart.registeredAddress
        || target.businessPeriod !== enterpriseInfo.value.jcEnterpriseInfoPart.businessPeriod
        || target.registeredCapital !== enterpriseInfo.value.jcEnterpriseInfoPart.registeredCapital) && !unref(changeBusinessLicenseAttachmentsList)) {
        ElMessage.warning('工商信息已修改,请重新上传营业执照')
        return
    }

    if ((target.contactName !== enterpriseInfo.value.jcEnterpriseInfoPart.contactName
        || target.contactMobile !== enterpriseInfo.value.jcEnterpriseInfoPart.contactMobile
        || target.contactCardNo !== enterpriseInfo.value.jcEnterpriseInfoPart.contactCardNo) && !unref(changeAttachmentsAuthorizationLetterList)
    ) {
        ElMessage.warning('联系人信息已修改,请重新上传授权函')
        return
    }
    const businessLicenseAttachmentsList = target.businessLicenseAttachmentsList.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    })
    const attachmentsAuthorizationLetterList = target.attachmentsAuthorizationLetterList.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    })
    const qualificationDocumentList = target.qualificationDocumentList?.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    }) || []
    const projectPerformanceList = target.projectPerformanceList?.map((v: any) => {
        return { fileName: v.name, fileUrl: v.url }
    }) || []
    const supplyCat = JSON.stringify(target?.supplyCat) ?? '[]'
    const cat = JSON.stringify(target?.cat) ?? '[]'
    const params = {
        ...target,
        attachmentsAuthorizationLetterList,
        businessLicenseAttachmentsList,
        cat,
        projectPerformanceList,
        qualificationDocumentList,
        supplyCat,
    }
    console.log(params, 'params')

    mutate(
        params,
        {
            onError(error) {
                console.log('🚀 ~ onError ~ error:', error)
            },
            onSuccess: () => {
                createMessage.success('操作成功')
            },
        },
    )
}

function goback() {
    go(-1)
}

defineExpose({
    state,
})
</script>

<template>
    <ElCard shadow="never">
        <div class="mb-20 text-16 font-700">
            企业信息
        </div>

        <SearchForm ref="formRef"
                    v-model="state"
                    :group="finalGroup"
                    submit-text="查询"
                    :has-footer="false"
                    label-position="top"
                    :rules="rules"
        >
            <template #group-header="{ title, icon }">
                <div>
                    <div v-if="title === '工商信息(数据来源于企查查)' "
                         class="p-5 bg-#fcf6ed leading-[32px]"
                    >
                        {{ state.auditStatusName }}

                        <div v-if="state.auditStatus === 2 && state.auditRemark">
                            驳回原因: {{ state.auditRemark }}
                        </div>
                    </div>

                    <span class="leading-[32px]">
                        {{ title }}
                        <el-icon> <component :is="icon" /> </el-icon>
                    </span>
                </div>
            </template>

            <template #plus-field-logo>
                <FlUpload :key="key"
                          v-model="state.logo"
                          tips
                          accept=".jpg,.jpeg,.png"
                          :disabled="disabled"
                          is-mall-admin
                />
            </template>

            <template #plus-field-businessLicenseAttachmentsList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="key"
                              v-model="state.businessLicenseAttachmentsList"
                              list-type="text"
                              :limit="1"
                              :file-size="10"
                              :accept="fileType"
                              is-mall-admin
                              :disabled="disabled"
                              @success="changeBusinessLicenseAttachmentsList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer">
                        最多上传一张
                    </div>
                </div>
            </template>

            <template #plus-field-attachmentsAuthorizationLetterList>
                <div flex
                     flex-col
                     w-full
                >
                    <FlUpload :key="key"
                              v-model="state.attachmentsAuthorizationLetterList"
                              list-type="text"
                              :limit="5"
                              :file-size="10"
                              :accept="fileType"
                              tips
                              is-mall-admin
                              :disabled="disabled"
                              @success="changeAttachmentsAuthorizationLetterList = true"
                    />

                    <div class="text-14 c-#86909C cursor-pointer"
                         @click="downTpl('授权函模板')"
                    >
                        <span class="c-#EA0000">下载</span>《授权函模板》
                    </div>
                </div>
            </template>

            <template #plus-field-qualificationDocumentList>
                <FlUpload :key="key"
                          v-model="state.qualificationDocumentList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          is-mall-admin
                          :disabled="disabled"
                />
            </template>

            <template #plus-field-projectPerformanceList>
                <FlUpload :key="key"
                          v-model="state.projectPerformanceList"
                          list-type="text"
                          :limit="5"
                          :file-size="10"
                          :accept="fileType"
                          tips
                          is-mall-admin
                          :disabled="disabled"
                />
            </template>
        </SearchForm>

        <template #footer>
            <div class="flex justify-center">
                <el-button type="info"
                           @click="goback"
                >
                    返回
                </el-button>

                <el-button type="primary"
                           :loading="isLoading"
                           @click="sumbit"
                >
                    提交
                </el-button>
            </div>
        </template>
    </ElCard>
</template>

<style lang="scss" scoped>
:deep(.logo-upload) {
    .el-upload {
        width: 100%;
    }
}

:deep(.el-card__header .leading-\[32px\]) {
    font-weight: 600;
}

.old :deep(.el-descriptions__body .el-descriptions__table) {
    background: #f7f8fa;
}

.new :deep(.el-descriptions__body .el-descriptions__table) {
    background: #f0fff0;
}
</style>
